package io.lkt.modules.sys.controller;

import io.lkt.common.util.Query;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.service.*;
import io.lkt.modules.sys.service.impl.BUserBrandInfoServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 用户品牌信息表
 *
 * @author xss
 * @email dustwas@163.com
 * @date 2019-03-11 14:40:57
 */
@RestController
@RequestMapping("/sys/buserbrandinfo")
public class BUserBrandInfoController extends AbstractController{

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    private BUserBrandInfoService bUserBrandInfoService;

    @Autowired
    private BBrandInfoService bBrandInfoService;

    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;

    @Autowired
    private BBrandSupplyInfoService bBrandSupplyInfoService;

    @Autowired
    BUserBrandInfoServiceImpl UserBrandInfoService;

    @Value("${serviceUrls}")
    private String serviceUrls;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:buserbrandinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        // yl 20200606 start
        SysUserEntity curUser = getUser();
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);
        // yl 20200606 end
        Query query = new Query(params);
        List<BUserBrandInfoEntity> brandList = bUserBrandInfoService.queryList(query);
//        for(BUserBrandInfoEntity brandInfo:brandList){
//            int total=bUserBrandInfoService.vipTotal(brandInfo.getBrandId());
//            //每日文章数
//            Map<String,Object> map=bUserBrandInfoService.articleTotal(brandInfo.getBrandId());
//            brandInfo.setArticleTotal(Integer.parseInt(map.get("articleTotal").toString()));
//            brandInfo.setArticleYesterday(Integer.parseInt(map.get("articleYesterday").toString()));
//            brandInfo.setArticleToday(Integer.parseInt(map.get("articleToday").toString()));
//            brandInfo.setTencentTotal(Integer.parseInt(map.get("tencentTotal").toString()));
//            brandInfo.setVipTotal(total);
//        }
        int total = bUserBrandInfoService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 品牌列表
     * @param params
     * @return
     */
    @RequestMapping("/queryList")
    @RequiresPermissions("sys:buserbrandinfo:list")
    public R queryList(@RequestParam Map<String, Object> params){
        // yl 20200606 start
        SysUserEntity curUser = getUser();
        List<SysUserGzhEntity> userGzhList = this.sysUserRoleService.queryGzhList(curUser.getUserId());
        params.put("userGzhList", userGzhList);
        // yl 20200606 end
        Query query = new Query(params);
        List<BUserBrandInfoEntity> brandList = bUserBrandInfoService.queryUser(query);
        int total = bUserBrandInfoService.queryUserTotal(query);
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:buserbrandinfo:info")
    public R info(@PathVariable("id") Integer id){
        BBrandInfoEntity bUserBrandInfo = bBrandInfoService.getById(id);

        // 补位文章品牌 id
        if(bUserBrandInfo != null && bUserBrandInfo.getLinkBrand() !=null){
            BBrandInfoEntity linkBrandNameInfo = this.bBrandInfoService.getById(bUserBrandInfo.getLinkBrand());
            if(linkBrandNameInfo != null && linkBrandNameInfo.getBrandName() != null) {
                bUserBrandInfo.setLinkBrandName(linkBrandNameInfo.getBrandName());
            }
        }

        // 补位文章分类 id
        if(bUserBrandInfo != null && bUserBrandInfo.getLinkType() != null) {
            BArticleTypeInfoEntity linkTypeNameInfo = this.bArticleTypeInfoService.getById(bUserBrandInfo.getLinkType());
            if (linkTypeNameInfo != null && linkTypeNameInfo.getArticleTypeName() != null) {
                bUserBrandInfo.setLinkTypeName(linkTypeNameInfo.getArticleTypeName());
            }
        }

        // 组装渲染绑定品牌名称
        String brandBindingIds = bUserBrandInfo.getBrandBindingIds();
        String brandBindingNames = "";
        if (brandBindingIds != null && !brandBindingIds.trim().equals("")) {
            String[] brandBindings = brandBindingIds.split(",");

            for (String brandNameInfo : brandBindings) {
                BBrandInfoEntity bBrandInfoEntity = bBrandInfoService.getById(Integer.valueOf(brandNameInfo));
                if(bBrandInfoEntity != null) {
                    brandBindingNames = brandBindingNames + "," + bBrandInfoEntity.getBrandName();
                }
            }
            brandBindingNames = brandBindingNames.substring(1);
            bUserBrandInfo.setBrandBindingNames(brandBindingNames);
        }
        System.out.println(bUserBrandInfo);
        List<BBrandInfoEntity> list=bBrandInfoService.typeByBrandId(id);
        list.removeAll(Collections.singleton(null));
        System.out.println(list.size()+">>>>>>>>>>>>>>");
        Map<String,Object> map=new HashMap<>();
        map.put("brandId",id);
        List<BBrandSupplyInfoEntity> supply=bBrandSupplyInfoService.queryList(map);
        String typeName="";
        if(supply.size()>0){
            if(supply.get(0).getArticleTypeId()==null) {
                typeName=null;
            }else{
                typeName = supply.get(0).getArticleTypeId().toString();
            }
        }
        System.out.println(typeName);
        return R.ok().put("bUserBrandInfo", bUserBrandInfo).put("list",list).put("typeName",typeName);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:buserbrandinfo:save")
    public R save(@RequestBody BUserBrandInfoEntity bUserBrandInfo){
        bUserBrandInfoService.save(bUserBrandInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("sys:buserbrandinfo:update")
    public R update(@RequestBody BUserBrandInfoEntity bUserBrandInfo){
        ValidatorUtils.validateEntity(bUserBrandInfo);
        bUserBrandInfoService.updateById(bUserBrandInfo);

        return R.ok();
    }

    /**
     * 修改用户品牌海报
     */
    @RequestMapping("/updateUserBrandPoster")
    public R updateUserBrandPoster(@RequestBody BUserBrandInfoEntity bUserBrandInfo){
        Integer id =  bUserBrandInfo.getId();
        String brandPoster = bUserBrandInfo.getBrandPoster();
        bUserBrandInfoService.updateUserBrandPoster(id, brandPoster);

        return R.ok();
    }

    /**
     * 合并品牌
     */
    @Transactional
    @RequestMapping("/merge")
    @RequiresPermissions("sys:buserbrandinfo:update")
    public R merge(@RequestBody BUserBrandInfoEntity bUserBrandInfo)throws Exception{
        ValidatorUtils.validateEntity(bUserBrandInfo);
        BBrandInfoEntity brandInfo=bBrandInfoService.queryByName(bUserBrandInfo.getBrandName());
        if(brandInfo==null){
            return R.error();
        }

        //原来别名
        String brandAlias = Optional.ofNullable(brandInfo.getBrandAlias()).orElse("");

        //原来关键字
        String brandKeyWord = Optional.ofNullable(brandInfo.getBrandKeyWord()).orElse("");

        Integer[] brandIds = bUserBrandInfo.getBrandIds();

        if(brandIds.length > 0){
            for(int i = 0; i < brandIds.length; i++) {
                BBrandInfoEntity brandInfoEntity = this.bBrandInfoService.queryNameById(brandIds[i]);
                //新加的品牌名称不为空才追加
                if(brandInfoEntity != null && brandInfoEntity.getBrandName() != null && !(brandInfoEntity.getBrandName().trim().equals(""))){
                    if(!brandAlias.contains(brandInfoEntity.getBrandName())){
                        if(brandAlias.equals("")){
                            brandAlias = brandAlias + brandInfoEntity.getBrandName();
                        }else{
                            brandAlias = brandAlias + ',' + brandInfoEntity.getBrandName();
                        }
                    }

                    if(!brandKeyWord.contains(brandInfoEntity.getBrandName())){
                        if(brandKeyWord.equals("")){
                            brandKeyWord = brandKeyWord + brandInfoEntity.getBrandName();
                        }else{
                            brandKeyWord = brandKeyWord + ',' + brandInfoEntity.getBrandName();
                        }

                    }
                }
            }
        }

        brandInfo.setBrandAlias(brandAlias);
        brandInfo.setBrandKeyWord(brandKeyWord);
        brandInfo.setModifyTime(new Date());
        bBrandInfoService.saveOrUpdate(brandInfo);

        bUserBrandInfo.setBrandId(brandInfo.getId());
        bUserBrandInfoService.mergeBrand(bUserBrandInfo);
        HttpClient httpClient = HttpClientBuilder.create().build();
//        HttpGet get = new HttpGet("https://service.rrdsp.cn/cache/delCache?key=com.tulele.vtool.mapper.UserBrandInfoMapper");
//        HttpResponse response = httpClient.execute(get);
//        String context= EntityUtils.toString(response.getEntity());
//        System.out.println(context);

        HttpGetPostUtils.delCache(serviceUrls,"UserBrandInfoMapper");

//        get = new HttpGet("https://service.rrdsp.cn/cache/delCache?key=com.tulele.vtool.mapper.BrandInfoMapper");
//        response = httpClient.execute(get);
//        context= EntityUtils.toString(response.getEntity());
//        System.out.println(context);

        HttpGetPostUtils.delCache(serviceUrls,"BrandInfoMapper");
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:buserbrandinfo:delete")
    public R delete(@RequestBody Integer[] ids){
        bUserBrandInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("/getUserBrand")
    public R getUserBrand(@RequestParam Map<String, Object> params) {
        if (StringUtils.isBlank(params.get("userId").toString())) {
            return R.error("用户不存在");
        }
        Query query = new Query(params);
        List<BUserBrandInfoEntity> list = bUserBrandInfoService.getUserBrand(query);
        int total = bUserBrandInfoService.getUserBrandCount(Integer.valueOf(params.get("userId").toString())).intValue();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("page", page);
    }

    @RequestMapping("/getUserBrandCount/{userId}")
    public R getUserBrandCount(@PathVariable("userId") Integer userId) {
        int userBrandCount = bUserBrandInfoService.getUserBrandCount(userId).intValue();
        return R.ok().put("userBrandCount", userBrandCount);
    }

    @RequestMapping("/simplyInfo/{id}")
    public R simplyInfo(@PathVariable("id") Integer id) {
        BUserBrandInfoEntity bUserBrandInfo = bUserBrandInfoService.getSimplyInfoById(id);
        return R.ok().put("bUserBrandInfo", bUserBrandInfo);
    }
}
